﻿using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint.WebPartPages;
using Microsoft.SharePoint;
using System.Collections.Generic;
using System.Linq;
using System.Web.UI.DataVisualization.Charting;
using System.Drawing;
using System.Data;
using System.Web.UI.HtmlControls;
using Microsoft.SharePoint.Utilities;
using System.Web;

namespace SharePoint2010Poll
{
    public partial class ShowPoll : UserControl
    {
        // Poll state is used to control what is displayed on the form
        public PollStates PollState
        {
            get
            {
                return (this.Parent as PollWebPart).PollState;
            }
            set
            {
                SPLimitedWebPartManager wpm =
                    SPContext.Current.Web.GetLimitedWebPartManager(Page.Request.Path, PersonalizationScope.Shared);
                try
                {
                    PollWebPart wp = wpm.WebParts[this.Parent.ID] as PollWebPart;
                    wpm.Web.AllowUnsafeUpdates = true;
                    wp.PollState = value;
                    wpm.SaveChanges(wp);
                }
                finally
                {
                    wpm.Web.AllowUnsafeUpdates = false;
                }
            }
        }
        public bool HasUserResponded
        {
            get;
            set;
        }

        public string PollId
        {
            get
            {
                return this.Parent.ID;
            }
        }

        PollsItem _poll;


        protected void Page_Load(object sender, EventArgs e)
        {
            btnSave.Click += new EventHandler(btnSave_Click);

            // If poll is configured
            // If poll is not configured, display a literal string
            if (this.PollState == PollStates.PollConfigured)
            {
                _poll = PollHelper.GetPoll(PollId);

                if (_poll != null)
                {
                    // Check if user has answered
                    // If user has answered, display response graph
                    // else display option grid

                    lblPollTitle.Text = _poll.Title;
                    lblPollQuestion.Text = _poll.Question;

                    this.HasUserResponded = PollHelper.HasUserResponded(SPContext.Current.Web.CurrentUser.LoginName, _poll.PollId);

                    if (HasUserResponded)
                    {
                        List<PollUserResponsesItem> userResponses = PollHelper.GetUserResponses(_poll.PollId);
                        DisplayResponseGraph(userResponses);
                    }
                    else
                    {
                        if (!Page.IsPostBack)
                        {
                            List<string> answers = PollHelper.GetAnswers(_poll.Answers);
                            DisplayResponseGrid(answers);
                        }
                    }

                    ToggleVisibility(HasUserResponded);
                }
            }
            else
            {
                this.Controls.Add(new LiteralControl("This Poll is not yet open for responses"));
            }
        }

        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);
            ToggleVisibility(this.HasUserResponded);
        }

        void btnSave_Click(object sender, EventArgs e)
        {
            PollUserResponsesItem responseItem = new PollUserResponsesItem();
            responseItem.Title = SPContext.Current.Web.CurrentUser.LoginName;
            responseItem.Answer = GetCurrentAnswer();
            responseItem.PollId = _poll.PollId;
            responseItem.UserId = SPContext.Current.Web.CurrentUser.LoginName;
            PollHelper.SaveUserResponse(responseItem);
            List<PollUserResponsesItem> userResponses = PollHelper.GetUserResponses(_poll.PollId);
            SPUtility.Redirect(Request.Url.ToString(), SPRedirectFlags.Default, HttpContext.Current);
            this.HasUserResponded = true;
            DisplayResponseGraph(userResponses);
        }

        private string GetCurrentAnswer()
        {
            if (rdoChoices.SelectedIndex > -1)
            {
                return rdoChoices.SelectedValue;
            }
            else
            {
                return string.Empty;
            }
        }

        private void ToggleVisibility(bool ShowResults)
        {
            phGraphResult.Visible = ShowResults;
            phPollChoices.Visible = !ShowResults;
        }

        internal void DisplayResponseGrid(List<string> answers)
        {
            rdoChoices.Items.Clear();
            foreach (string answer in answers)
            {
                rdoChoices.Items.Add(new ListItem(answer, answer));
            }
        }

        internal void DisplayResponseGraph(List<PollUserResponsesItem> UserResponses)
        {
            if (_poll != null)
            {
                List<string> answers = PollHelper.GetAnswers(_poll.Answers);
                List<ResponseCount> responseCountForGraph = new List<ResponseCount>();

                foreach (string answer in answers)
                {
                    int currentResponseCount = (from responses in UserResponses
                                                where responses.Answer == answer
                                                select responses).Count();
                    responseCountForGraph.Add(new ResponseCount()
                    {
                        Response = answer,
                        Count = currentResponseCount,
                        Percentage = ((currentResponseCount / answers.Count) * 100)
                    });
                }

                DrawPieStyleCharts(responseCountForGraph);
            }
        }

        /// <summary>
        /// Draw the pie style charts
        /// </summary>
        private void DrawPieStyleCharts(List<ResponseCount> UserResponses)
        {

            // Create new data series and set it's visual attributes
            Series series = new Series("Results");
            series.ChartType = SeriesChartType.Pie;
            series.IsValueShownAsLabel = true;
            series.BorderWidth = 1;
            series.ShadowOffset = 2;

            foreach (ResponseCount responseItem in UserResponses)
            {
                //get item info
                string answer = responseItem.Response;
                int count = responseItem.Count;
                decimal percentage = responseItem.Percentage;

                //add point
                DataPoint item = new DataPoint();
                item.AxisLabel = answer;
                item.Label = " "; //make sure it is empty
                item.ToolTip = string.Format("{0} vote(s), {1}", count, percentage.ToString("P"));
                item.SetValueY(count);
                series.Points.Add(item);
            }


            chartDisplay.Series.Add(series);

            chartDisplay.Width = (this.Parent as System.Web.UI.WebControls.WebParts.WebPart).Width;
            if (chartDisplay.Width == 0)
            {
                chartDisplay.Width = 300;
            }
            chartDisplay.Height = (this.Parent as System.Web.UI.WebControls.WebParts.WebPart).Height;
            if (chartDisplay.Height == 0)
            {
                chartDisplay.Height = 300;
            }

            //Draw a legend
            // Add header separator to the table
            chartDisplay.Legends.Add("Legend"); ;
            chartDisplay.Legends["Legend"].HeaderSeparator = LegendSeparatorStyle.Line;
            chartDisplay.Legends["Legend"].HeaderSeparatorColor = Color.Gray;
            chartDisplay.Legends["Legend"].Docking = Docking.Bottom;

            // Add Color column      
            LegendCellColumn colorColumn = new LegendCellColumn();
            colorColumn.ColumnType = LegendCellColumnType.SeriesSymbol;
            colorColumn.HeaderText = "Color";
            colorColumn.HeaderBackColor = Color.WhiteSmoke;
            chartDisplay.Legends["Legend"].CellColumns.Add(colorColumn);

            // Add answer cell column      
            LegendCellColumn answerColumn = new LegendCellColumn();
            answerColumn.ColumnType = LegendCellColumnType.Text;
            answerColumn.Text = "#AXISLABEL";
            answerColumn.HeaderText = "Answer";
            answerColumn.HeaderBackColor = Color.WhiteSmoke;
            chartDisplay.Legends["Legend"].CellColumns.Add(answerColumn);

            // Add vote cell column      
            LegendCellColumn votesColumn = new LegendCellColumn();
            votesColumn.Text = "#VALY";
            votesColumn.HeaderText = "Votes";
            votesColumn.HeaderBackColor = Color.WhiteSmoke;
            chartDisplay.Legends["Legend"].CellColumns.Add(votesColumn);

            // Add percentage cell column      
            LegendCellColumn percentageColumn = new LegendCellColumn();
            percentageColumn.Text = "#PERCENT";
            percentageColumn.HeaderText = "Percentage";
            percentageColumn.HeaderBackColor = Color.WhiteSmoke;
            chartDisplay.Legends["Legend"].CellColumns.Add(percentageColumn);
        }
    }
}
